package com.bhs.sansong.ui.shipments;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Typeface;
import android.util.ArrayMap;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;

import com.bhs.sansong.R;
import com.bhs.sansong.base.BaseFragment;
import com.bhs.sansong.bean.AddressInfo;
import com.bhs.sansong.bean.SpecialLineData;
import com.bhs.sansong.bean.TimeBean;
import com.bhs.sansong.net.NetCallBack;
import com.bhs.sansong.utils.DateUtils;
import com.bhs.sansong.utils.FastCilckOneUtil;
import com.bhs.sansong.utils.LogUtils;
import com.bhs.sansong.utils.MyUtils;
import com.bhs.sansong.utils.ToastUtil;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;

import java.sql.Time;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 首页选择地址
 */
public class SelectAddressFragment extends BaseFragment implements View.OnClickListener, NetCallBack {

    private TextView mTvTopSpeed;
    private TextView mTvDesignate;
    private LinearLayout mLlShipmentsInfo;
    private TextView mTvDepartureAddress;
    private TextView mTvDepartureInfo;
    private LinearLayout mLlShipments;
    private FrameLayout mFlExchange;
    private LinearLayout mLlReceiveInfo;
    private TextView mTvDeliveryAddress;
    private TextView mTvDeliveryInfo;
    private LinearLayout mLlReceive;
    private TextView mTvPlaceOrder;
    private TextView mTvSubscribe;
    private ActivityResultLauncher<Intent> intentActivityResultLauncher;
    private AddressInfo shipAddress, shippingAddress;
    private String order_type = "2";
    private boolean isOpen;
    private String displayTime;
    private String uploadTime;


    public static SelectAddressFragment newInstance() {
        return new SelectAddressFragment();
    }


    @Override
    public int initLayout() {
        return R.layout.fragment_select_address;
    }

    @Override
    public void initView(View root) {
        mTvTopSpeed = root.findViewById(R.id.tv_top_speed);
        mTvTopSpeed.setOnClickListener(this);
        mTvDesignate = root.findViewById(R.id.tv_designate);
        mTvDesignate.setOnClickListener(this);
        mLlShipmentsInfo = root.findViewById(R.id.ll_shipments_info);
        mTvDepartureAddress = root.findViewById(R.id.tv_departure_address);
        mTvDepartureInfo = root.findViewById(R.id.tv_departure_info);
        mLlShipments = root.findViewById(R.id.ll_shipments);
        mFlExchange = root.findViewById(R.id.fl_exchange);
        mLlReceiveInfo = root.findViewById(R.id.ll_receive_info);
        mTvDeliveryAddress = root.findViewById(R.id.tv_delivery_address);
        mTvDeliveryInfo = root.findViewById(R.id.tv_delivery_info);
        mLlReceive = root.findViewById(R.id.ll_receive);
        mTvPlaceOrder = root.findViewById(R.id.tv_place_order);
        mTvSubscribe = root.findViewById(R.id.tv_subscribe);
        mTvSubscribe.setOnClickListener(this);
        mTvPlaceOrder.setOnClickListener(this);
        mLlShipments.setOnClickListener(this);
        mLlReceiveInfo.setOnClickListener(this);
        mLlShipmentsInfo.setOnClickListener(this);
        mLlReceive.setOnClickListener(this);
        mFlExchange.setOnClickListener(this);
        root.findViewById(R.id.tv_shipments_address_book).setOnClickListener(this);
        root.findViewById(R.id.tv_receive_address_book).setOnClickListener(this);
        root.findViewById(R.id.tv_shipments_address_book2).setOnClickListener(this);
        root.findViewById(R.id.tv_receive_address_book2).setOnClickListener(this);
    }

    @Override
    public void prestrain() {
        super.prestrain();
        intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                //此处是跳转的result回调方法
                if (result.getData() != null) {
                    if (result.getResultCode() == 1) {
                        shipAddress = result.getData().getParcelableExtra("info");
                        setShipAddress();
                    } else {
                        shippingAddress = result.getData().getParcelableExtra("info");
                        setShippingAddress();
                    }
                    getSpecialLineList();
                }
            }
        });
    }

    private void getSpecialLineList() {
        if (shipAddress == null || shippingAddress == null) {
            return;
        }
        isOpen = false;
        Map<String, String> map = new ArrayMap();
        map.put("start_city", shipAddress.getCity());
        map.put("end_city", shippingAddress.getCity());
        map.put("page", "1");
        map.put("limit", "2");
        networkRequest(netApi.get_special_line_list(map), this, 999);
    }

    @SuppressLint("SetTextI18n")
    private void setShipAddress() {
        if (shipAddress != null) {
            mLlShipments.setVisibility(View.GONE);
            mLlShipmentsInfo.setVisibility(View.VISIBLE);
            mTvDepartureAddress.setText(shipAddress.getCity() + shipAddress.getAddress());
            mTvDepartureInfo.setText(String.format("%s %s", shipAddress.getTruename(),
                    MyUtils.phoneHide(shipAddress.getMobile())));
        } else {
            mLlShipments.setVisibility(View.VISIBLE);
            mLlShipmentsInfo.setVisibility(View.GONE);
        }
    }

    @SuppressLint("SetTextI18n")
    private void setShippingAddress() {
        if (shippingAddress != null) {
            mLlReceive.setVisibility(View.GONE);
            mLlReceiveInfo.setVisibility(View.VISIBLE);
            mTvDeliveryAddress.setText(shippingAddress.getCity() + shippingAddress.getAddress());
            mTvDeliveryInfo.setText(String.format("%s %s", shippingAddress.getTruename(),
                    MyUtils.phoneHide(shippingAddress.getMobile())));
        } else {
            mLlReceive.setVisibility(View.VISIBLE);
            mLlReceiveInfo.setVisibility(View.GONE);
        }
    }


    @Override
    public void initData() {
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        if (FastCilckOneUtil.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.ll_shipments:
            case R.id.ll_shipments_info:
                Intent intent = new Intent(getContext(), CompleteAddressActivity.class);
                intent.putExtra("type", 1);
                intentActivityResultLauncher.launch(intent);
                break;
            case R.id.ll_receive:
            case R.id.ll_receive_info:
                Intent intent2 = new Intent(getContext(), CompleteAddressActivity.class);
                intent2.putExtra("type", 2);
                intentActivityResultLauncher.launch(intent2);
                break;
            case R.id.tv_place_order:
                if (shipAddress == null) {
                    ToastUtil.show("请完善发货信息");
                    return;
                }
                if (shippingAddress == null) {
                    ToastUtil.show("请完善收货信息");
                    return;
                }
                if (!isOpen) {
                    ToastUtil.show("此城市还没开通专线");
                    return;
                }
                startActivity(new Intent(getContext(), IssueNewOrderActivity.class)
                        .putExtra("order_type", order_type)
                        .putExtra("shippingAddress", shippingAddress)
                        .putExtra("shipAddress", shipAddress));

                break;
            case R.id.tv_top_speed:
                order_type = "2";
                mTvDesignate.setBackground(null);
                mTvTopSpeed.setBackgroundResource(R.drawable.bg_top_white_16);
                mTvTopSpeed.setTypeface(Typeface.DEFAULT_BOLD);
                mTvDesignate.setTypeface(Typeface.DEFAULT);
                break;
            case R.id.tv_designate:
                order_type = "1";
                mTvTopSpeed.setBackground(null);
                mTvDesignate.setBackgroundResource(R.drawable.bg_top_white_16);
                mTvDesignate.setTypeface(Typeface.DEFAULT_BOLD);
                mTvTopSpeed.setTypeface(Typeface.DEFAULT);
                break;
            case R.id.fl_exchange:
                AddressInfo temp = shipAddress;
                shipAddress = shippingAddress;
                shippingAddress = temp;
                setShipAddress();
                setShippingAddress();
                getSpecialLineList();
                break;
            case R.id.tv_shipments_address_book:
            case R.id.tv_shipments_address_book2:
                Intent intent3 = new Intent(getContext(), AddressBookActivity.class);
                intent3.putExtra("type", 1);
                intentActivityResultLauncher.launch(intent3);
                break;
            case R.id.tv_receive_address_book:
            case R.id.tv_receive_address_book2:
                Intent intent4 = new Intent(getContext(), AddressBookActivity.class);
                intent4.putExtra("type", 2);
                intentActivityResultLauncher.launch(intent4);
                break;
            case R.id.tv_subscribe:
                if (shippingAddress == null || shipAddress == null) {
                    ToastUtil.show("请完善地址信息");
                    return;
                }
                if (!isOpen) {
                    ToastUtil.show("此城市还没开通专线");
                    return;
                }
                //条件选择器
                if (pvOptions == null) {
                    getTimeData();
                    pvOptions = new OptionsPickerBuilder(getContext(), new OnOptionsSelectListener() {
                        @Override
                        public void onOptionsSelect(int options1, int option2, int options3, View v) {
                            //上传给接口的时间
                            uploadTime = list1.get(options1).getFormattingTime()
                                    + " " + list2.get(options1).get(option2).getTime()
                                    + ":" + list3.get(options1).get(option2).get(options3).getTime();
                            //显示时间
                            displayTime = list1.get(options1).getPickerViewText()
                                    + " " + list2.get(options1).get(option2).getTime()
                                    + ":" + list3.get(options1).get(option2).get(options3).getTime();
                            LogUtils.d(uploadTime + "==" + displayTime);

                            startActivity(new Intent(getContext(), IssueNewOrderActivity.class)
                                    .putExtra("order_type", order_type)
                                    .putExtra("shippingAddress", shippingAddress)
                                    .putExtra("shipAddress", shipAddress)
                                    .putExtra("uploadTime", uploadTime)
                                    .putExtra("displayTime", displayTime));
                        }
                    }).build();
                    pvOptions.setPicker(list1, list2, list3);
                }
                pvOptions.show();
                break;
        }
    }

    private OptionsPickerView<TimeBean> pvOptions;
    private List<TimeBean> list1;
    private List<List<TimeBean>> list2;
    private List<List<List<TimeBean>>> list3;

    private void getTimeData() {
        list1 = new ArrayList<>();
        list2 = new ArrayList<>();
        list3 = new ArrayList<>();

        long timeMillis = System.currentTimeMillis();
        int day = 86400000;
        list1.add(new TimeBean("今天", DateUtils.getYearMonthDay(timeMillis), 1));
        list1.add(new TimeBean("明天", DateUtils.getYearMonthDay(timeMillis + day), 1));
        list1.add(new TimeBean("后天", DateUtils.getYearMonthDay(timeMillis + (day * 2)), 1));

        final Calendar mCalendar = Calendar.getInstance();
        int mHour = mCalendar.get(Calendar.HOUR_OF_DAY);
        for (int i = 0; i < list1.size(); i++) {
            List<TimeBean> data = new ArrayList<>();
            for (int j = 0; j < 24; j++) {
                if (j <= mHour && i == 0) {
                    continue;
                }
                if (j < 10) {
                    data.add(new TimeBean(String.format("0%s", j), 2));
                } else {
                    data.add(new TimeBean(String.format("%s", j), 2));
                }
            }
            list2.add(data);
        }


        for (int i = 0; i < list1.size(); i++) {
            List<List<TimeBean>> data2 = new ArrayList<>();
            for (int j = 0; j < list2.get(i).size(); j++) {
                List<TimeBean> data = new ArrayList<>();
                for (int k = 0; k < 6; k++) {
                    if (k == 0) {
                        data.add(new TimeBean("00", 3));
                    } else {
                        data.add(new TimeBean(String.format("%s", k * 10), 3));
                    }
                }
                data2.add(data);
            }
            list3.add(data2);
        }
    }

    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if (requestCode == 999) {
            SpecialLineData specialLineData = new Gson().fromJson(json, SpecialLineData.class);
            if (specialLineData.isStatus()) {
                isOpen = specialLineData.getData().getTotal_count() > 0;
            }
        }
    }

    @Override
    public void onFailure(int requestCode) {

    }
}